<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        html,
        body,
        #container {
          width: 100%;
          height: 100%;
        }
    </style>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: "51f6623971cf8da6e494a34b5b950758",
    };
</script>
<script src="https://webapi.amap.com/loader.js"></script>
<script type="text/javascript">
    var map;
    AMapLoader.load({
      key: "5b131ecf85d77d41cdba47a989b8bb76", //申请好的Web端开发者 Key，调用 load 时必填
      version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    })
      .then((AMap) => {
        map = new AMap.Map("container");
      })
      .catch((e) => {
        console.error(e); //加载错误提示
      });
</script>
<script>
    // 1
    // window.onmessage = (event) => {

    // }
    // 2
    var port;
    window.addEventListener("message", (event) => {
      if (event.data === "mess_port") {
        port = event.ports[0]; // 拿到的端口
        onNativeMessage();
        sendMessage({ type: "success", value: "接收到端口" });
      }
    });
    // 发送消息
    function sendMessage(obj) {
      if (port) {
        if (typeof obj !== "string") {
          port.postMessage(JSON.stringify(obj));
        } else {
          port.postMessage(obj);
        }
      }
    }

    function onNativeMessage() {
      if (port) {
        port.onmessage = (event) => {
          let location = JSON.parse(event.data);
          map.setCenter([location.longitude, location.latitude]);
          map.setZoom(13);
        };
      }
    }
</script>
</body>
</html>
